
//
//  PersonalInfoViewController.m
//  Luxury
//
//  Created by DCQ on 2018/5/18.
//  Copyright © 2018年 ZNXZ. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "PersonalInfoCell.h"
#import "PortraitCell.h"
#import "GSPickerView.h"
#import "ChangeNameViewController.h"
#import "LoginViewController.h"
#import "UserInfoModel.h"
#import "LGTabbarViewController.h"
#import "AppDelegate.h"

#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImagePickerController.h"
#import "TZImageManager.h"

NSString * const PersonalInfoCellIdentifier = @"PersonalInfoCellIdentifier";
NSString * const PortraitCellIdentifier = @"PortraitCellIdentifier";
@interface PersonalInfoViewController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic, copy) NSString * nickName;
@property(nonatomic, copy) NSString * birthday;
@property(nonatomic, copy) NSString * sex;
@property(nonatomic, copy) NSString * userImgUrl;
@property (nonatomic,strong)GSPickerView *pickerView;
@property(nonatomic, strong) NSMutableArray *selectedPhotos;//图片数据
@property(nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation PersonalInfoViewController
- (GSPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[GSPickerView alloc]initWithFrame:self.view.bounds];
        _pickerView.buttonColor = UIColorFromRGB(0x49BAFF);
        _pickerView.titleColor = UIColorFromRGB(0x000000);
        _pickerView.titleBgColor = UIColorFromRGB(0xF6F6F6);
    }
    return _pickerView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItemTitle: @"个人信息"];
    [self setupBottomView];
    [self updateUserInfo];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfo) name:@"USER_LOGIN_SUCCESSFUL" object:nil];
}
- (void)updateUserInfo{
    self.userImgUrl = UserInfo.avatar_url;
    if ([UserInfo.gender integerValue] ==0) {
        self.sex = @"女";
    }else if ([UserInfo.gender integerValue] == 1){
        self.sex = @"男";
    }
    
    self.nickName = UserInfo.nickname;
    self.birthday = UserInfo.birthday;
    [self.tableView reloadData];
}
- (void)setupBottomView{
    CGFloat bottomHeight = 50;
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height-bottomHeight, self.view.frame.size.width, bottomHeight)];
    [bottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bottomView];
    
    UIButton * exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitBtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
    [exitBtn setBackgroundColor:UIColorFromRGB(0xDFDFDF)];
    [exitBtn addTarget:self action:@selector(exitAction) forControlEvents:UIControlEventTouchUpInside];
    [exitBtn setFrame:CGRectMake(20, 5, self.view.frame.size.width -40, bottomHeight- 10)];
    exitBtn.layer.cornerRadius = (bottomHeight- 10)/2;
    exitBtn.layer.masksToBounds =  YES;
    exitBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bottomView addSubview:exitBtn];
}

- (void)registerCell{
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PortraitCell class]) bundle:nil] forCellReuseIdentifier:PortraitCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PersonalInfoCell class]) bundle:nil] forCellReuseIdentifier:PersonalInfoCellIdentifier];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 50;
    if (indexPath.row == 0) {
        height = 60;
    }
    return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = nil;
    if (indexPath.row == 0) {
       
        PortraitCell * tempCell = [tableView dequeueReusableCellWithIdentifier:PortraitCellIdentifier];
        [tempCell setupUserImg: self.userImgUrl];
        cell = tempCell;
    }else{
        PersonalInfoCell * tempCell = [tableView dequeueReusableCellWithIdentifier:PersonalInfoCellIdentifier];
        [self configCell:tempCell whithIndexPath:indexPath];
        cell = tempCell;
    }
    
    return cell;
}

- (void)configCell:(PersonalInfoCell *)cell whithIndexPath:(NSIndexPath *)indexPath{
    NSString * title =  [self getTitles][indexPath.row-1];
    NSString * content = nil;
    if (indexPath.row == 1) {
        content = self.nickName;
    }else if (indexPath.row == 2) {
         content = self.sex;
    }else if (indexPath.row == 3) {
         content = self.birthday;
    }
    
    [cell setupTitle:title withContent:content];
}

- (NSArray *)getTitles{
    NSArray * temps = @[@"昵称",@"性别",@"生日"];
    return temps;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [self showImgVActionSheetView];
    }else if (indexPath.row == 1) {
        [self changeName];
    }else if (indexPath.row == 2) {
        [self changeSex];
    }else if (indexPath.row == 3) {
        [self changeBirthday];
    }
    
}

- (void)changeBirthday{
    
    [self.pickerView appearWithTitle:@"请选择生日" pickerType:GSPickerTypeDatePicker subTitles:nil selectedStr:self.birthday  sureAction:^(NSInteger path, NSString *pathStr) {
        
        NSDictionary * params = @{@"token":UserInfo.userToken, @"birthday":pathStr };
        WEAKSELF
        [[MainApi sharedInstance] postPath:@"User/profile" params:params  resultBlock:^(NSDictionary *responseObject, NSError *error) {
            STRONGSELF
            strongSelf.birthday = pathStr;
            [strongSelf.tableView reloadData];
        }];
       
    } cancleAction:^{
        
    }];
}
- (void)changeSex{
    
    [self.pickerView appearWithTitle:@"请选择性别" pickerType:GSPickerTypeOneComponentPicker subTitles:@[@"男",@"女"] selectedStr:self.sex  sureAction:^(NSInteger path, NSString *pathStr) {
        NSString * gender = @"0";
        if ([pathStr isEqualToString:@"男"]) {
            gender = @"1";
        }
        NSDictionary * params = @{@"token":UserInfo.userToken, @"gender":gender };
        WEAKSELF
        [[MainApi sharedInstance] postPath:@"User/profile" params:params  resultBlock:^(NSDictionary *responseObject, NSError *error) {
            STRONGSELF
            strongSelf.sex = pathStr;
            [strongSelf.tableView reloadData];
        }];
       
    } cancleAction:^{
        
    }];
}

- (void)changeName{
    
    ChangeNameViewController * changeNameVC = [[ChangeNameViewController alloc]initWithNibName:NSStringFromClass([ChangeNameViewController class]) bundle:nil];
    changeNameVC.changeBlock = ^(NSString *nickName) {
        self.nickName = nickName;
        [self.tableView reloadData];
    };
    [self.navigationController pushViewController:changeNameVC animated:YES];
    
}
- (void)exitAction{
    
    [UserInfo clearAllUserInfo];
    [self gotoLoginVC];
}
- (void)gotoLoginVC{
     AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
     LGTabbarViewController * tabbarVC =  (LGTabbarViewController *)appDelegate.window.rootViewController;
    LoginViewController * loginVC = [[LoginViewController alloc]initWithNibName:NSStringFromClass([LoginViewController class]) bundle:nil];
    loginVC.exitCancelBlock = ^{
        [self.navigationController popToRootViewControllerAnimated:NO];
        tabbarVC.selectedIndex = 0;
    };
    UINavigationController * nv = [[UINavigationController alloc]initWithRootViewController:loginVC];
    [self presentViewController:nv animated:YES completion:nil];
}

#pragma mark ---

- (void)showImgVActionSheetView{
    UIAlertController *actionSheet=[UIAlertController alertControllerWithTitle:@"上传头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *otherAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actoin){
        [self takePhoto];
    }];//在代码块中可以填写具体这个按钮执行的操作
    [actionSheet addAction:otherAction];
    
    UIAlertAction *otherAction2 =[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actoin){
        [self pushImagePickerController];
    }];//在代码块中可以填写具体这个按钮执行的操作
    [actionSheet addAction:otherAction2];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *acton){
        
    }];//创建按钮cancel以及对应事件
    [actionSheet addAction:cancelAction];
    //弹出视图
    [self presentViewController: actionSheet animated:YES completion:nil];
}


#pragma mark - TZImagePickerController

- (void)showNormalAlertTitle:(NSString *)title content:(NSString *)message   otherAction:(UIAlertAction *)otherAction{
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle: title message:message preferredStyle:UIAlertControllerStyleAlert];//创建界面
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *acton){
        
    }];//创建按钮cancel以及对应事件
  
    //最后将这些按钮都添加到界面上去，显示界面
    [alertController addAction:cancelAction];
    if (otherAction) {
       [alertController addAction:otherAction];
    }
    [self presentViewController: alertController animated:YES completion:nil];
}
- (void)takePhoto {
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
//        // 无相机权限 做一个友好的提示
//        //        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
//        //        [alert show];
//
//        [self showNormalAlertTitle:@"无法使用相机" content:@"请在iPhone的""设置-隐私-相机""中允许访问相机" otherAction:nil];
//        // 拍照之前还需要检查相册权限
//    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
//
//        [self showNormalAlertTitle:@"无法访问相册" content:@"请在iPhone的""设置-隐私-相册""中允许访问相册" otherAction:nil];
//
//
//    } else if ([TZImageManager authorizationStatus] == 0) { // 正在弹框询问用户是否允许访问相册，监听权限状态
//
//        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
//            [self takePhoto];
//        }];
//
//
//    } else {
//        [self gotoImagePickerV];
//    }
}

- (void)gotoImagePickerV{
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            self.imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
         [self presentViewController:self.imagePickerVc animated:YES completion:nil];
        
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (IOS9) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

- (void)pushImagePickerController {
    int  MAX_IMAGE_COUNT = 1;
    int  COLUMN_IMAGE_COUNT =  4;
    if ( MAX_IMAGE_COUNT  <= 0) {
        return;
    }
    
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:MAX_IMAGE_COUNT columnNumber:COLUMN_IMAGE_COUNT delegate:self pushPhotoPickerVc:YES];
    
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    
    if (MAX_IMAGE_COUNT > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.circleCropRadius = 100;
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    //imagePickerVc.allowPreview = NO;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
//    [imagePickerVc setNaviBgColor:project_main_blue];
//    [imagePickerVc setNaviTitleFont:fontSize_18];
    
    [imagePickerVc setDoneBtnTitleStr:@"确定"];
    
    [imagePickerVc setOKButtonTitleColorNormal:[UIColor whiteColor]];
    [imagePickerVc setOKButtonTitleColorDisabled:[UIColor lightGrayColor]];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                WEAKSELF
//                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
//                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
//                        [tzImagePickerVc hideProgressHUD];
//                        TZAssetModel *assetModel = [models firstObject];
//                        if (tzImagePickerVc.sortAscendingByModificationDate) {
//                            assetModel = [models lastObject];
//                        }
//                        [weakSelf refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
//                        
//                    }];
//                }];
                
            }
        }];
    }
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    
    self.selectedPhotos = [NSMutableArray arrayWithObject:image];
    self.selectedAssets = [NSMutableArray arrayWithObject:asset];
    [self uploadImgV];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    [self uploadImgV];
}
- (void)uploadImgV{
    NSDictionary * params = @{@"token":UserInfo.userToken};
    NSMutableDictionary * fileDic = [NSMutableDictionary dictionary];
    for (int i =0;i<[self.selectedAssets count] ;i++) {
        UIImage * image = self.selectedPhotos[i];
        
        
        NSString * fileName = @"file";
//        if (iOS8Later) {
//
//            PHAsset * asset = self.selectedAssets[i];
//            fileName= asset.localIdentifier;
//            //            NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
//            //            fileName = ((PHAssetResource*)resources[0]).originalFilename;
//        } else {
//            ALAsset * asset = self.selectedAssets[i];
//            fileName =  asset.defaultRepresentation.filename;
//
//        }
        
        [fileDic setObject:image forKey: fileName];
    }
    if ([self.selectedAssets count] > 0) {
        [[MainApi sharedInstance] sendPostUploadFilePath:@"User/uploadAvatar" params:params fileDic:fileDic  resultBlock:^(NSDictionary *responseObject, NSError *error) {
            NSDictionary * tempDic = responseObject[@"data"]; 
            if (tempDic[@"url"]) {
                UserInfo.avatar_url = tempDic[@"url"];
            }
            [self updateUserInfo];
        }];
        
    }
}
@end
